<template>
  <el-container>
    <el-header>
      <router-link :to="{ name: 'Home' }" class="gotohome"
        ><h1>前端题库网</h1></router-link
      >
    </el-header>
    <el-main>
      <div class="mainbox">
        <el-form
          class="inpbox"
          :model="loginform"
          :rules="formrules"
          ref="formref"
        >
          <h2>登录</h2>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginform.username"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="loginform.password" type="password"></el-input>
          </el-form-item>

          <el-form-item class="btn">
            <el-button type="info" plain @click="login">登录</el-button>
            <!-- 重置表单功能 -->
            <el-button type="info" plain @click="tosignup"
              >无账号，去注册</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-main>
    <el-footer> xxx科技©2021 All rights reserved admin@xxxxxxxx.com </el-footer>
  </el-container>
</template>

<script>
import {apiLogin} from '../api/user'
export default {
  data() {
    return {
      loginform: {
        username: "admin",
        password: "123456",
      },

      formrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {},
  methods: {
    tosignup() {
      this.$router.push("/signup");
    },
    login() {
      this.$refs.formref.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        const res = await apiLogin(this.loginform);
        console.log(res);
        if (res.data.state !== 200) {
          return this.$message.error("登录失败，用户名不存在或密码错误");
        }

        this.$message.success("登录成功");
        this.$store.commit("user/SET_USER_MESSAGE", res.data);
        this.$router.push("/home");
      });
    },
  },
};
</script>

<style scoped>
.el-container {
  width: 100vw;
  height: 100vh;
}
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-header h1 {
  margin-left: 20%;
  float: left;
  line-height: 50%;
}
.el-main {
  background-color: #e9eef3;
  color: #333;
  display: flex;
  align-items: center;
}

.mainbox {
  margin: 0 auto;
  width: 30%;
  height: 40%;
  background-color: #b3c0d1;
  display: flex;
  align-items: center;
}
.el-input {
  width: 70%;
}
.inpbox {
  text-align: right;
  margin: 0 auto;
  width: 80%;
}
.inpbox h2 {
  text-align: center;
}
.gotohome {
  color: black;
}

a {
  text-decoration: none;
}

.mainbox .inpbox  .el-form-item__content .el-form-item__error{
  left: 40% !important;
}
</style>